<template>
  <div class="text2img-template">
    <div class="header">
      <h2>文生图模板</h2>
      <div class="actions desktop-only">
        <el-button @click="$router.back()">返回</el-button>
        <el-button type="primary" @click="generateImage" :loading="generating">
          生成图片
        </el-button>
      </div>
      <!-- 移动端顶部操作栏 -->
      <div class="mobile-header-actions mobile-only">
        <el-button icon-only circle @click="$router.back()">
          <el-icon><ArrowLeft /></el-icon>
        </el-button>
      </div>
    </div>

    <MobileFormControls 
      submitText="生成图片" 
      :loading="generating"
      @submit="generateImage"
      :showFixedControls="!showMobilePreview && generatedImages.length === 0"
    >
      <div class="main-content">
        <!-- 左侧参数配置 -->
        <div class="params-section" :class="{ 'mobile-hidden': showMobilePreview && generatedImages.length > 0 }">
          <el-form 
            ref="formRef"
            :model="formData"
            :label-width="mobileLabelWidth"
            class="template-form"
          >
            <el-card class="form-card">
              <template #header>
                <div class="card-header">
                  <span>基础参数</span>
                </div>
              </template>

              <el-form-item label="提示词" prop="prompt">
                <el-input
                  v-model="formData.prompt"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入图片描述"
                />
              </el-form-item>

              <el-form-item label="反向提示词" prop="negative_prompt">
                <el-input
                  v-model="formData.negative_prompt"
                  type="textarea"
                  :rows="2"
                  placeholder="请输入不需要的元素描述"
                />
              </el-form-item>

              <el-form-item label="图片尺寸" prop="size">
                <el-select v-model="formData.size" style="width: 100%">
                  <el-option label="512 x 512" value="512x512" />
                  <el-option label="768 x 768" value="768x768" />
                  <el-option label="1024 x 1024" value="1024x1024" />
                </el-select>
              </el-form-item>

              <el-form-item label="生成数量" prop="batch_size">
                <el-input-number 
                  v-model="formData.batch_size"
                  :min="1"
                  :max="4"
                  style="width: 100%"
                />
              </el-form-item>
            </el-card>

            <el-card class="form-card">
              <el-form-item label="采样步数" prop="steps">
                <el-slider
                  v-model="formData.steps"
                  :min="20"
                  :max="50"
                  :step="1"
                  show-input
                />
              </el-form-item>

              <el-form-item label="CFG Scale" prop="cfg_scale">
                <el-slider
                  v-model="formData.cfg_scale"
                  :min="1"
                  :max="20"
                  :step="0.5"
                  show-input
                />
              </el-form-item>

              <el-form-item label="种子" prop="seed">
                <div class="seed-input">
                  <el-input-number 
                    v-model="formData.seed"
                    :min="-1"
                    :max="2147483647"
                    controls-position="right"
                    style="width: calc(100% - 80px)"
                  />
                  <el-button @click="formData.seed = -1" class="random-seed-btn">
                    随机
                  </el-button>
                </div>
              </el-form-item>
            </el-card>
          </el-form>
        </div>

        <!-- 右侧图片显示 -->
        <div class="preview-section" :class="{ 'mobile-fullscreen': showMobilePreview && generatedImages.length > 0 }">
          <div v-if="!generating && generatedImages.length === 0" class="empty-preview">
            <div class="empty-preview-content">
              <el-icon class="empty-icon"><Picture /></el-icon>
              <p>生成结果将显示在这里</p>
            </div>
          </div>
          
          <!-- 进度显示 -->
          <div v-if="generating" class="progress-bar">
            <div class="progress-header">
              <span class="progress-title">生成进度</span>
              <span class="progress-percentage">{{ currentProgress }}%</span>
            </div>
            <el-progress 
              :percentage="currentProgress" 
              :stroke-width="15"
              :show-text="false"
              :status="currentProgress >= 100 ? 'success' : ''"
            />
            <div class="node-info" v-if="currentNodeInfo">
              <el-tag size="small" effect="plain">{{ currentNodeInfo.node }}</el-tag>
              <span>{{ currentNodeInfo.description || '' }}</span>
            </div>
            <div class="progress-detail">
              <el-icon v-if="currentProgress < 100"><Loading /></el-icon>
              <el-icon v-else><SuccessFilled /></el-icon>
              {{ progressDetail || '准备中...' }}
            </div>
          </div>

          <el-card v-if="generatedImages.length > 0" class="result-card">
            <template #header>
              <div class="card-header">
                <span>生成结果</span>
                <!-- 移动端返回表单按钮 -->
                <el-button 
                  v-if="showMobilePreview" 
                  size="small" 
                  class="mobile-only"
                  @click="showMobilePreview = false"
                >
                  返回表单
                </el-button>
              </div>
            </template>
            <div class="image-grid">
              <div 
                v-for="(image, index) in generatedImages" 
                :key="index"
                class="image-item"
                @click="openImagePreview(image)"
              >
                <img :src="image.url" :alt="`生成图片 ${index + 1}`" />
                <div class="image-actions">
                  <el-button size="small" circle @click.stop="downloadImage(image)">
                    <el-icon><Download /></el-icon>
                  </el-button>
                </div>
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </MobileFormControls>

    <!-- 图片预览弹窗 -->
    <el-dialog
      v-model="previewVisible"
      :title="previewTitle"
      width="80%"
      class="image-preview-dialog"
      :append-to-body="true"
    >
      <div class="preview-image-container">
        <img v-if="previewImage" :src="previewImage.url" class="preview-image" />
      </div>
      <div class="preview-actions">
        <el-button type="primary" @click="downloadImage(previewImage)">
          <el-icon><Download /></el-icon> 下载图片
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { request } from '@/utils/request'
import { wsService } from '@/services/websocket.service'
import type { GeneratedImage } from '@/types/comfyui'
import type { 
  WorkflowResponse, 
  WorkflowNode, 
  WorkflowJson,
  GenerationResult,
  GenerationOutput,
  GenerationResponse,
  GenerationStatusResponse
} from '@/types/workflow'
import { io, Socket } from 'socket.io-client'
import { Loading, SuccessFilled, Download, RefreshLeft, ArrowLeft, RefreshRight, Picture } from '@element-plus/icons-vue'
import { da } from 'element-plus/es/locale/index.mjs'
import MobileFormControls from '@/components/MobileFormControls.vue'

const route = useRoute()
const router = useRouter()
const formRef = ref()
const generating = ref(false)
const showAdvanced = ref(false)
const generatedImages = ref<GeneratedImage[]>([])
const currentProgress = ref(0)
const progressDetail = ref('')
const currentNodeInfo = ref<{node: string; description?: string} | null>(null)

// WebSocket 相关状态
const socket = ref<Socket | null>(null)
const wsConnected = ref(false)

// 默认参数
const formData = ref({
  prompt: '',
  negative_prompt: '',
  size: '512x512',
  batch_size: 1,
  sampler: 'Euler a',
  steps: 30,
  cfg_scale: 7,
  seed: -1
})

interface ComfyUIOutput {
  images: Array<{
    filename: string;
    type?: string;
    subfolder?: string;
  }>;
}

interface ComfyUIOutputs {
  [key: string]: ComfyUIOutput;
}

// 参数预设
interface Preset {
  name: string;
  params: typeof formData.value;
}

const presets = ref<Preset[]>([
  {
    name: '默认设置',
    params: {
      prompt: '',
      negative_prompt: 'blurry, low quality, watermark',
      size: '512x512',
      batch_size: 1,
      sampler: 'Euler a',
      steps: 30,
      cfg_scale: 7,
      seed: -1
    }
  }
]);
const currentPreset = ref('');

// 加载预设
const loadPreset = (presetName: string) => {
  const preset = presets.value.find(p => p.name === presetName);
  if (preset) {
    formData.value = { ...preset.params };
    ElMessage.success(`已加载预设: ${presetName}`);
  }
};

// 保存当前设置为预设
const saveCurrentPreset = async () => {
  try {
    const name = await ElMessageBox.prompt('请输入预设名称', '保存预设', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
    });
    
    if (name.value) {
      // 检查预设名是否已存在
      const existingIndex = presets.value.findIndex(p => p.name === name.value);
      
      if (existingIndex >= 0) {
        // 更新现有预设
        presets.value[existingIndex].params = { ...formData.value };
        ElMessage.success(`预设 "${name.value}" 已更新`);
      } else {
        // 创建新预设
        presets.value.push({
          name: name.value,
          params: { ...formData.value }
        });
        ElMessage.success(`预设 "${name.value}" 已保存`);
      }
      
      currentPreset.value = name.value;
    }
  } catch (e) {
    // 用户取消
  }
};

// 获取工作流参数
const fetchWorkflowParams = async (workflowId: string) => {
  try {
    console.log('正在获取工作流参数，ID:', workflowId);
    
    // 尝试从API获取工作流数据
    let response;
    try {
      response = await request(`/api/v1/workflows/${workflowId}`);
      console.log('API响应:', response);
    } catch (apiError) {
      console.error('API请求失败:', apiError);
      // API请求失败，使用模拟数据
      response = getMockWorkflow(workflowId);
    }
    
    // 如果没有获取到工作流JSON，使用模拟数据
    if (!response?.workflow_json) {
      console.warn('工作流JSON不存在，使用模拟数据');
      response = getMockWorkflow(workflowId);
    }
    
    // 创建临时表单数据对象
    const tempFormData = { ...formData.value };
    
    // 遍历所有节点获取默认值
    for (const [nodeId, node] of Object.entries<WorkflowNode>(response.workflow_json)) {
      if (!node || !node.class_type || !node.inputs) continue;
      
      console.log(`处理节点 ${nodeId}:`, node);

      switch (node.class_type) {
        case 'KSampler': {
          console.log('找到KSampler节点:', node.inputs);
          const inputs = node.inputs;
          tempFormData.sampler = String(inputs.sampler_name || 'Euler a');
          tempFormData.steps = Number(inputs.steps || 30);
          tempFormData.cfg_scale = Number(inputs.cfg || 7);
          tempFormData.seed = Number(inputs.seed || -1);
          break;
        }
        
        case 'CLIPTextEncode': {
          console.log('找到CLIPTextEncode节点:', node.inputs);
          const text = node.inputs.text;
          if (text) {
            const isNegative = text.toLowerCase().includes('negative') || 
                             text.toLowerCase().includes('watermark');
            if (isNegative) {
              tempFormData.negative_prompt = text;
            } else {
              tempFormData.prompt = text;
            }
          }
          break;
        }
        
        case 'EmptyLatentImage': {
          console.log('找到EmptyLatentImage节点:', node.inputs);
          const inputs = node.inputs;
          const width = Number(inputs.width || 512);
          const height = Number(inputs.height || 512);
          tempFormData.size = `${width}x${height}`;
          tempFormData.batch_size = Number(inputs.batch_size || 1);
          break;
        }
      }
    }
    
    // 更新表单数据
    formData.value = tempFormData;
    console.log('表单数据已更新:', formData.value);
    
  } catch (error) {
    console.error('获取工作流参数失败:', error);
    ElMessage.warning('获取工作流参数失败，已加载默认参数');
    
    // 加载默认参数
    formData.value = {
      prompt: '一张美丽的风景画，湖泊，山脉，蓝天',
      negative_prompt: 'blurry, low quality, watermark, text, signature',
      size: '512x512',
      batch_size: 1,
      sampler: 'Euler a',
      steps: 30,
      cfg_scale: 7,
      seed: -1
    };
  }
};

// 获取模拟工作流数据
const getMockWorkflow = (workflowId: string) => {
  console.log('使用模拟工作流数据，ID:', workflowId);
  
  // 根据ID返回不同的模拟数据
  const mockWorkflows: Record<string, any> = {
    '1': {
      workflow_json: {
        'clip_encode': {
          class_type: 'CLIPTextEncode',
          inputs: {
            text: '一张美丽的风景画，湖泊，山脉，蓝天'
          }
        },
        'clip_encode_neg': {
          class_type: 'CLIPTextEncode',
          inputs: {
            text: 'blurry, low quality, watermark, text, signature'
          }
        },
        'sampler': {
          class_type: 'KSampler',
          inputs: {
            seed: -1,
            steps: 30,
            cfg: 7,
            sampler_name: 'Euler a'
          }
        },
        'latent': {
          class_type: 'EmptyLatentImage',
          inputs: {
            width: 512,
            height: 512,
            batch_size: 1
          }
        }
      }
    },
    // 可以添加更多模拟工作流
  };
  
  // 返回对应ID的模拟数据，如果没有则返回默认数据
  return mockWorkflows[workflowId] || mockWorkflows['1'];
};

// 生成图片
const generateImage = async () => {
  if (generating.value) return;
  
  try {
    // // 检查用户是否登录
    // const token = localStorage.getItem('token');
    // if (!token) {
    //   ElMessageBox.confirm(
    //     '生成图片需要登录，是否前往登录页面？',
    //     '未登录提示',
    //     {
    //       confirmButtonText: '去登录',
    //       cancelButtonText: '取消',
    //       type: 'warning'
    //     }
    //   ).then(() => {
    //     // 保存当前页面路径，登录后可以返回
    //     router.push({
    //       path: '/login',
    //       query: { redirect: router.currentRoute.value.fullPath }
    //     });
    //   }).catch(() => {
    //     // 用户取消登录
    //     ElMessage.info('您取消了登录');
    //   });
    //   return;
    // }
    
    generating.value = true;
    currentProgress.value = 0;
    progressDetail.value = '准备中...';
    generatedImages.value = [];
    
    // 验证工作流ID，优先使用id参数，兼容旧版的workflow_id参数
    const workflowId = route.query.id || route.query.workflow_id;
    if (!workflowId || typeof workflowId !== 'string') {
      throw new Error('无效的工作流ID');
    }

    // 验证必要参数
    if (!formData.value.prompt) {
      throw new Error('请输入提示词');
    }

    // 准备参数
    const params = {
      workflow_id: workflowId,
      params: {
        prompt: formData.value.prompt,
        negative_prompt: formData.value.negative_prompt,
        size: formData.value.size,
        batch_size: formData.value.batch_size,
        sampler: formData.value.sampler,
        steps: formData.value.steps,
        cfg_scale: formData.value.cfg_scale,
        seed: formData.value.seed
      }
    };

    console.log('生成参数:', params);

    // 尝试发送生成请求
    let response;
    try {
      response = await request<GenerationResponse>('/api/v1/workflows/generate', {
        method: 'POST',
        body: params
      });

      if (!response?.success) {
        throw new Error(response?.message || '生成失败');
      }

      console.log('生成任务创建成功:', response);
      
      // 订阅WebSocket更新
      if (response.prompt_id) {
        wsService.subscribeToTask(response.prompt_id);
      }
    } catch (apiError) {
      console.error('API请求失败:', apiError);
      // API请求失败，使用模拟生成
      simulateGeneration();
    }

  } catch (error) {
    console.error('生成图片失败:', error);
    ElMessage.error({
      message: '生成失败: ' + (error instanceof Error ? error.message : '未知错误'),
      duration: 5000
    });
    generating.value = false;
  }
};

// 模拟生成过程
const simulateGeneration = () => {
  console.log('使用模拟生成流程');
  
  // 模拟进度更新
  let progress = 0;
  const progressInterval = setInterval(() => {
    progress += Math.random() * 5;
    if (progress > 100) progress = 100;
    
    // 更新进度
    currentProgress.value = Math.floor(progress);
    
    // 模拟节点信息
    const nodeInfo = getStageFromProgress(currentProgress.value);
    currentNodeInfo.value = nodeInfo;
    progressDetail.value = nodeInfo.description;
    
    // 完成时
    if (progress >= 100) {
      clearInterval(progressInterval);
      setTimeout(() => {
        // 模拟生成结果
        simulateGenerationResult();
      }, 500);
    }
  }, 300);
};

// 模拟生成结果
const simulateGenerationResult = () => {
  // 根据提示词选择不同的模拟图片
  const prompt = formData.value.prompt.toLowerCase();
  
  // 模拟图片URL（可以替换为实际的示例图片）
  let imageUrl = 'https://source.unsplash.com/random/512x512/?landscape';
  
  if (prompt.includes('人物') || prompt.includes('人像') || prompt.includes('portrait')) {
    imageUrl = 'https://source.unsplash.com/random/512x512/?portrait';
  } else if (prompt.includes('动物') || prompt.includes('宠物') || prompt.includes('animal')) {
    imageUrl = 'https://source.unsplash.com/random/512x512/?animal';
  } else if (prompt.includes('城市') || prompt.includes('建筑') || prompt.includes('city')) {
    imageUrl = 'https://source.unsplash.com/random/512x512/?city';
  } else if (prompt.includes('食物') || prompt.includes('美食') || prompt.includes('food')) {
    imageUrl = 'https://source.unsplash.com/random/512x512/?food';
  }
  
  // 创建模拟图片结果
  const mockImages: GeneratedImage[] = [];
  
  // 根据batch_size生成多张图片
  for (let i = 0; i < formData.value.batch_size; i++) {
    // 添加随机参数避免缓存
    const randomParam = Math.floor(Math.random() * 1000000);
    mockImages.push({
      url: `${imageUrl}&random=${randomParam}`,
      filename: `generated_${Date.now()}_${i}.png`,
      width: 512,
      height: 512
    });
  }
  
  // 更新UI
  generatedImages.value = mockImages;
  generating.value = false;
  ElMessage.success('生成成功（模拟模式）');
};

// WebSocket 事件处理函数
const handleProgress = (data: any) => {
  console.log('Generation progress data:', data);
  
  try {
    // 解析后端传递的数据
    if (data && typeof data === 'object') {
      // 获取进度值和节点信息
      let progressValue = 0;
      let nodeInfo = null;
      
      // 处理直接传递的 comfyui_data 数据
      if (data.comfyui_data) {
        const comfyData = data.comfyui_data;
        
        // 处理不同类型的 ComfyUI 消息
        if (comfyData.value !== undefined && comfyData.max) {
          // 计算百分比进度
          progressValue = Math.round((comfyData.value / comfyData.max) * 100);
          nodeInfo = {
            node: comfyData.node || '处理中',
            description: getNodeDescription(comfyData.node)
          };
        }
      } 
      // 处理简化的进度信息
      else if (data.progress !== undefined) {
        progressValue = Math.max(0, Math.min(100, Number(data.progress)));
        nodeInfo = getStageFromProgress(progressValue);
      }
      
      // 更新 UI 状态
      currentProgress.value = progressValue;
      if (nodeInfo) {
        currentNodeInfo.value = nodeInfo;
        progressDetail.value = nodeInfo.description;
      }
    }
  } catch (error) {
    console.error('处理进度数据失败:', error);
    // 错误处理，但不中断用户体验
  }
};

// 获取节点对应的描述
const getNodeDescription = (nodeName: string): string => {
  if (!nodeName) return '处理中...';
  
  const nodeDescriptions: Record<string, string> = {
    'KSampler': '生成图像中...',
    'CLIPTextEncode': '编码提示词...',
    'EmptyLatentImage': '创建画布...',
    'VAEDecode': '解码图像...',
    'SaveImage': '保存图像...',
    // 其他节点类型可以在这里添加
  };
  
  return nodeDescriptions[nodeName] || `处理节点: ${nodeName}`;
};

// 根据进度百分比推测当前处理阶段
const getStageFromProgress = (progress: number): {node: string; description: string} => {
  if (progress < 5) {
    return { node: 'CLIPTextEncode', description: '处理提示词中...' };
  } else if (progress < 15) {
    return { node: 'EmptyLatentImage', description: '创建图像空间...' };
  } else if (progress < 85) {
    return { node: 'KSampler', description: `生成图像中... (${progress}%)` };
  } else if (progress < 95) {
    return { node: 'VAEDecode', description: '解码图像中...' };
  } else {
    return { node: 'SaveImage', description: '保存图像中...' };
  }
};

// 提取图片函数
const extractImages = (data: any): GeneratedImage[] => {
  const images: GeneratedImage[] = [];
  
  // 尝试从不同格式的数据中提取图片
  try {
    // 检查是否有images数组
    if (data.images && Array.isArray(data.images)) {
      return data.images.map((img: any) => ({
        url: img.url,
        filename: img.filename || 'image.png',
        width: img.width,
        height: img.height
      }));
    }
    
    // 检查ComfyUI格式
    if (data.outputs) {
      for (const [nodeId, output] of Object.entries(data.outputs)) {
        if (output && (output as any).images) {
          const outputImages = (output as any).images;
          if (Array.isArray(outputImages)) {
            const comfyuiUrl = import.meta.env.COMFYUI_API_URL || 'http://192.168.1.9:8188';
            outputImages.forEach((img: any) => {
              if (img.filename) {
                images.push({
                  url: `${comfyuiUrl}/view?filename=${img.filename}`,
                  filename: img.filename,
                  width: img.width,
                  height: img.height
                });
              }
            });
          }
        }
      }
    }
  } catch (error) {
    console.error('提取图片失败:', error);
  }
  
  return images;
};

// 处理完成事件
const handleComplete = (data: any) => {
  console.log('Generation complete:', data);
  generating.value = false;
  currentProgress.value = 100;
  progressDetail.value = '生成完成';
  
  // 提取生成的图片
  const images = extractImages(data);
  
  if (images.length > 0) {
    generatedImages.value = images;
    ElMessage.success('生成成功');
  } else {
    // 使用递归搜索查找图片
    const alternativeImages: GeneratedImage[] = [];
    
    const findImages = (obj: any, path = '') => {
      if (!obj || typeof obj !== 'object') return;
      console.log('obj:', obj);
      console.log('path:', path);
      // 检查是否有图片相关属性
      if (obj.filename && typeof obj.filename === 'string' && obj.filename.match(/\.(png|jpg|jpeg|webp)$/i)) {
        const subfolder = path.split('/').filter(Boolean).join('/');
        const comfyuiUrl = import.meta.env.COMFYUI_API_URL || 'http://192.168.1.9:8188';
        console.log('2path:', path);
        alternativeImages.push({
          //url: `${comfyuiUrl}/view?filename=${obj.filename}${subfolder ? `&subfolder=${subfolder}` : ''}`,
          url: `${comfyuiUrl}/view?filename=${obj.filename}`,
          filename: obj.filename,
          path: path
        });
      }
      
      // 递归搜索
      if (Array.isArray(obj)) {
        obj.forEach((item, index) => findImages(item, `${path}/${index}`));
      } else {
        Object.entries(obj).forEach(([key, value]) => findImages(value, `${path}/${key}`));
      }
    };
    
    findImages(data);
    
    if (alternativeImages.length > 0) {
      console.log('使用备选方法提取的图片:', alternativeImages);
      generatedImages.value = alternativeImages;
      ElMessage.success('生成成功');
      return;
    }
    
    ElMessage.error('未找到生成的图片');
  }
};

const handleError = (data: any) => {
  console.log('Generation error data:', JSON.stringify(data, null, 2));
  
  generating.value = false;
  currentProgress.value = 0;
  progressDetail.value = '';
  
  // 从不同可能的位置提取错误信息
  const errorMessage = 
    data.message || 
    data.error || 
    data.data?.error || 
    data.data?.message || 
    '生成失败';
    
  ElMessage.error(errorMessage);
};

// 处理生成完成
const handleGenerationComplete = (outputs: ComfyUIOutputs) => {
  try {
    console.log('处理生成输出:', outputs);

    if (!outputs || typeof outputs !== 'object') {
      throw new Error('无效的输出数据');
    }

    // 确保ComfyUI API URL有效
    const comfyuiUrl = import.meta.env.COMFYUI_API_URL || 'http://192.168.1.9:8188';
    console.log('使用ComfyUI URL:', comfyuiUrl);

    // 打印完整的输出结构以便调试
    console.log('输出数据结构:', JSON.stringify(outputs, null, 2));

    // 获取图片列表（适配ComfyUI输出格式）
    const images = Object.entries(outputs)
      .filter(([nodeId, output]) => {
        // 更详细的过滤逻辑，确保我们能获取到图片
        console.log(`节点 ${nodeId} 输出:`, output);
        return output && output.images && Array.isArray(output.images) && output.images.length > 0;
      })
      .flatMap(([nodeId, output]) => {
        console.log(`提取节点 ${nodeId} 的图片:`, output.images);
        return output.images.map(image => ({
          //url: `${comfyuiUrl}/view?filename=${image.filename}${image.subfolder ? `&subfolder=${image.subfolder}` : ''}`,
          url: `${comfyuiUrl}/view?filename=${image.filename}`,
          filename: image.filename,
          nodeId: nodeId  // 记录来源节点，方便调试
        }));
      });

    console.log('提取的图片:', images);

    if (images.length === 0) {
      // 使用递归搜索查找图片
      const alternativeImages: GeneratedImage[] = [];
      
      const findImages = (obj: any, path = '') => {
        if (!obj || typeof obj !== 'object') return;
        
        if (obj.filename && typeof obj.filename === 'string') {
          const subfolder = obj.subfolder || '';
          alternativeImages.push({
            //url: `${comfyuiUrl}/view?filename=${obj.filename}${subfolder ? `&subfolder=${subfolder}` : ''}`,
            url: `${comfyuiUrl}/view?filename=${obj.filename}`,
            filename: obj.filename,
            path: path
          });
        }
        
        // 递归查找
        for (const key in obj) {
          findImages(obj[key], `${path}.${key}`);
        }
      };
      
      for (const key in outputs) {
        findImages(outputs[key], key);
      }
      
      if (alternativeImages.length > 0) {
        console.log('使用备选方法提取的图片:', alternativeImages);
        generatedImages.value = alternativeImages;
        ElMessage.success('生成成功');
        return;
      }
      
      throw new Error('未生成任何图片');
    }

    // 更新显示
    generatedImages.value = images;
    ElMessage.success('生成成功');
  } catch (error) {
    console.error('处理生成结果失败:', error);
    ElMessage.error(error instanceof Error ? error.message : '处理生成结果失败');
  }
};

// 移动端相关状态
const showMobilePreview = ref(false);
const mobileLabelWidth = computed(() => window.innerWidth < 768 ? 'auto' : '120px');

// 图片预览相关
const previewVisible = ref(false);
const previewImage = ref<GeneratedImage | null>(null);
const previewTitle = computed(() => '图片预览');

// 图片预览
const openImagePreview = (image: GeneratedImage) => {
  previewImage.value = image;
  console.log('openImagePreview:', image);
  previewVisible.value = true;
};

// 图片复用
const useAsInput = (image: GeneratedImage) => {
  // Reuse the image parameters
  ElMessage.info('已复用参数，点击生成即可');
};

// 下载图片
const downloadImage = async (image: GeneratedImage | null) => {
  if (!image) return;
  
  try {
    const response = await fetch(image.url);
    const blob = await response.blob();
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = image.filename;
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
    document.body.removeChild(a);
  } catch (error) {
    console.error('下载图片失败:', error);
    ElMessage.error('下载图片失败');
  }
};

// 生命周期钩子
onMounted(() => {
  // 从URL获取工作流ID，优先使用id参数，兼容旧版的workflow_id参数
  const workflowId = route.query.id || route.query.workflow_id;
  if (workflowId) {
    console.log('Loading workflow:', workflowId);
    fetchWorkflowParams(workflowId as string);
  }

  // 设置 WebSocket 事件监听
  wsService.on('generation_progress', handleProgress);
  wsService.on('generation_complete', handleComplete);
  wsService.on('generation_error', handleError);
});

onUnmounted(() => {
  // 移除事件监听
  wsService.off('generation_progress', handleProgress);
  wsService.off('generation_complete', handleComplete);
  wsService.off('generation_error', handleError);
});
</script>

<style lang="scss" scoped>
@use '@/assets/styles/responsive.scss' as responsive;

.text2img-template {
  padding: 20px;
  min-height: calc(100vh - 60px);
  display: flex;
  flex-direction: column;
  position: relative;
  
  @include responsive.respond-to('sm') {
    padding: 16px;
    padding-bottom: 70px; // 为底部操作栏留出空间
  }
  
  @include responsive.respond-to('xs') {
    padding: 12px;
    padding-bottom: 70px;
  }
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  h2 {
    margin: 0;
    font-size: 24px;
  }
  
  .actions, .mobile-header-actions {
    display: flex;
    gap: 10px;
  }
}

.main-content {
  display: flex;
  gap: 20px;
  flex: 1;
  min-height: 0;
  
  @include responsive.respond-to('sm') {
    flex-direction: column;
  }
  
  @include responsive.respond-to('lg') {
    gap: 16px;
  }
  
  @include responsive.respond-to('md') {
    flex-direction: column;
  }
}

.params-section, .preview-section {
  flex: 1;
  
  @include responsive.respond-to('sm') {
    width: 100%;
    transition: all 0.3s ease;
  }
}

.params-section {
  flex: 0 0 500px;
  overflow-y: auto;
  
  @include responsive.respond-to('lg') {
    flex: 0 0 450px;
  }
  
  @include responsive.respond-to('md') {
    flex: 0 0 auto;
  }
  
  @include responsive.respond-to('sm') {
    &.mobile-hidden {
      display: none;
    }
  }
}

.preview-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16px;
  overflow-y: auto;
  @include responsive.respond-to('sm') {
    &.mobile-fullscreen {
     position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 70px;
      z-index: 100;
      background-color: #fff;
      padding: 16px;
    }
  }
}

.form-card {
  margin-bottom: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .header-with-switch {
    display: flex;
    align-items: center;
    gap: 10px;
  }
}

.preset-controls {
  display: flex;
  gap: 10px;
  align-items: center;
}

.seed-input {
  display: flex;
  align-items: center;
  gap: 10px;
  
  .random-seed-btn {
    flex-shrink: 0;
  }
}

.progress-bar {
  background-color: #f5f7fa;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 20px;
  
  .progress-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 8px;
  }
  
  .progress-title {
    font-weight: 500;
  }
  
  .progress-percentage {
    font-weight: 500;
  }
  
  .progress-detail {
    margin-top: 8px;
    display: flex;
    align-items: center;
    gap: 8px;
    color: #606266;
    font-size: 14px;
  }
  
  .node-info {
    margin-top: 8px;
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 14px;
  }
}

.result-card {
  .image-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 16px;
    
    @include responsive.respond-to('sm') {
      grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
      gap: 10px;
    }
  }
  
  .image-item {
    position: relative;
    border-radius: 8px;
    overflow: hidden;
    cursor: pointer;
    
    img {
      width: 100%;
      height: auto;
      display: block;
      transition: transform 0.3s;
    }
    
    &:hover {
      img {
        transform: scale(1.05);
      }
      
      .image-actions {
        opacity: 1;
      }
    }
    
    .image-actions {
      position: absolute;
      bottom: 8px;
      right: 8px;
      display: flex;
      gap: 8px;
      opacity: 0;
      transition: opacity 0.3s;
      
      @include responsive.respond-to('sm') {
        opacity: 1;
      }
    }
  }
}

.empty-preview {
  height: 100%;
  min-height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border-radius: 8px;
  
  .empty-preview-content {
    text-align: center;
    color: #909399;
    
    .empty-icon {
      font-size: 48px;
      margin-bottom: 16px;
    }
    
    p {
      margin: 0;
    }
  }
}

.image-preview-dialog {
  .preview-image-container {
    display: flex;
    justify-content: center;
    
    .preview-image {
      max-width: 100%;
      max-height: 70vh;
    }
  }
  
  .preview-actions {
    margin-top: 20px;
    display: flex;
    justify-content: center;
    gap: 16px;
  }
}

.mobile-only {
  display: none;
  
  @include responsive.respond-to('sm') {
    display: flex;
  }
}

.desktop-only {
  @include responsive.respond-to('sm') {
    display: none;
  }
}
</style> 